package com.lty.nettyhello.server;

import static org.jboss.netty.buffer.ChannelBuffers.copiedBuffer;

import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.ChannelBuffers;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ChannelStateEvent;
import org.jboss.netty.channel.ExceptionEvent;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.SimpleChannelHandler;
/**
 * 消息接受处理类
 * @author -琴兽-
 *
 */
public class HelloHandler extends SimpleChannelHandler {

	/**
	 * 接收消息
	 * 
	 * 
	 * StringDecoder 源码------------------------->
		@Override
	    protected Object decode(
	            ChannelHandlerContext ctx, Channel channel, Object msg) throws Exception {
	        if (!(msg instanceof ChannelBuffer)) {
	            return msg;
	        }
	        return ((ChannelBuffer) msg).toString(charset);
	    }
	 * 
	 * 
	 * StringEncoder 源码------------------------->
	 * 
	 * @Override
    	protected Object encode(
            ChannelHandlerContext ctx, Channel channel, Object msg) throws Exception {
        if (msg instanceof String) {
            return copiedBuffer(
                    ctx.getChannel().getConfig().getBufferFactory().getDefaultOrder(), (String) msg, charset);
        }

        return msg;
    }
	 * 
	 */
	@Override
	public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
		//不加StringDecoder解码器场景
//		ChannelBuffer msg = (ChannelBuffer) e.getMessage();
//		byte[] bytes = msg.array();
//		String content = new String(bytes);
//		System.out.println(content);
		
		//接收到的字符串内容，若没有设置字符串解码器e.getMessage()是ChannelBuffer
		String s = (String) e.getMessage();
		System.out.println(s);
		
		//通过通道ChannelBuffer -> ctx.getChannel()回写数据，若没有设置字符串编码器不能直接回写字符串，需要回写ChannelBuffer
		//不加StringEncoder解码器场景
//		ChannelBuffer copiedBuffer = ChannelBuffers.copiedBuffer("hi".getBytes());
//		ctx.getChannel().write(copiedBuffer);
		
		//ctx.getChannel()获取服务端通道
		ctx.getChannel().write("hi");
		super.messageReceived(ctx, e);
	}

	/**
	 * 捕获异常
	 */
	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception {
		System.out.println("exceptionCaught");
		super.exceptionCaught(ctx, e);
	}

	/**
	 * 新连接
	 */
	@Override
	public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
		System.out.println("channelConnected");
		super.channelConnected(ctx, e);
	}

	/**
	 * 必须是链接已经建立，关闭通道的时候才会触发
	 */
	@Override
	public void channelDisconnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
		System.out.println("channelDisconnected");
		super.channelDisconnected(ctx, e);
	}

	/**
	 * channel关闭的时候触发(关闭通道，回收资源)
	 */
	@Override
	public void channelClosed(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
		System.out.println("channelClosed");
		super.channelClosed(ctx, e);
	}
}
